package com.mengxuegu.gateway.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class TokenUtil {
    /**
     * 获取token
     *
     * @param exchange
     * @return
     */
    public static String getToken(ServerWebExchange exchange) {
        List<String> list = exchange.getRequest().getHeaders().get("Authorization");
        String token = null;
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        String tokenStr = list.get(0);
        if (StrUtil.isBlank(tokenStr)) {
            return null;
        }
        if(tokenStr.contains(" ")) {
            token = tokenStr.split(" ")[1];
        }
        return token;
    }

    /**
     * 没有token
     *
     * @param exchange
     * @return
     */
    public static Mono<Void> noTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.HTTP_UNAUTHORIZED);
        json.put("data", "网关校验系统未登入请先登入");
        return jsonToMono(json, exchange);
    }

    /**
     * 将json字符串转换为Mono的格式,并添加到相应中去
     *
     * @param json
     * @param exchange
     * @return
     */
    public static Mono<Void> jsonToMono(JSONObject json, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = json.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        response.setStatusCode(org.springframework.http.HttpStatus.valueOf(HttpStatus.HTTP_UNAUTHORIZED));
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * 无效的token
     *
     * @param exchange
     * @return
     */
    public static Mono<Void> invalidTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.HTTP_UNAUTHORIZED);
        json.put("data", "网关校验无效的token");
        return jsonToMono(json, exchange);
    }
}
